//
//  HUDManage.m
//  kzyjsq
//
//  Created by 李含文 on 2018/12/3.
//  Copyright © 2018年 李含文. All rights reserved.
//

#import "HUDManage.h"
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"

#define hud_bgColor [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7]
static MBProgressHUD *_MBPHUD;
static HUDManage * hw_HUDManage;

@interface HUDManage()<MBProgressHUDDelegate>

@end

@implementation HUDManage
+ (HUDManage *)shared {
    static dispatch_once_t once;
    dispatch_once(&once,^{
        hw_HUDManage = [[self alloc] init];
    });
    return hw_HUDManage;
}

- (void)hudWasHidden:(MBProgressHUD *)hud {
    _MBPHUD = nil;
}
+ (void)showHUDWithTitle:(NSString *)title {
    [self showHUDWithTitle:title afterDelay:0.8];
}
+ (void)showHUDWithTitle:(NSString *)title afterDelay:(NSTimeInterval)delay {
    if (title.length == 0) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismiss];
        UIWindow *view = [self topWindow];
        // 快速显示一个提示信息
        _MBPHUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
        _MBPHUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        _MBPHUD.bezelView.color = hud_bgColor;
        _MBPHUD.delegate = [HUDManage shared];
        _MBPHUD.detailsLabel.text = title;
        _MBPHUD.detailsLabel.font = [UIFont systemFontOfSize:14];
        _MBPHUD.contentColor = UIColor.whiteColor;
        _MBPHUD.mode = MBProgressHUDModeText;
        _MBPHUD.userInteractionEnabled = NO;
        // 隐藏时候从父控件中移除
        _MBPHUD.removeFromSuperViewOnHide = YES;
        [_MBPHUD hideAnimated:YES afterDelay:delay];
    });
}
+ (void)showLoadingHUD {
    [self showLoadingHUDWithTitle:@""];
}
+ (void)showLoadingHUDWithTitle:(NSString *)title {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismiss];
        UIWindow *view = [self topWindow];
        // 快速显示一个提示信息
        _MBPHUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
        _MBPHUD.mode = MBProgressHUDModeCustomView;
        
        UIImage *image = [[UIImage imageNamed:@"loading"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
        CABasicAnimation *anima = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        anima.toValue = @(M_PI*2);
        anima.duration = 1.0f;
        anima.repeatCount = MAXFLOAT;
        [imgView.layer addAnimation:anima forKey:nil];
        _MBPHUD.customView = imgView;
        _MBPHUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        _MBPHUD.bezelView.color = UIColor.whiteColor;
        _MBPHUD.animationType = MBProgressHUDAnimationFade;

//        CALayer *layer = [[CALayer alloc] init];
//        layer.frame = _MBPHUD.bezelView.bounds;//CGRectMake(0, 0, 50, 50);
//        layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
//        layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
//        layer.shadowOpacity = 0.1;//阴影透明度，默认0
//        layer.shadowRadius = 3;//阴影半径，默认3
//        [_MBPHUD.bezelView.layer insertSublayer:layer atIndex:0];
//        _MBPHUD.bezelView.borderColor = [UIColor.blueColor colorWithAlphaComponent:0.02];
//        _MBPHUD.bezelView.borderWidth = 2;
//        _MBPHUD.bezelView.layer.masksToBounds = NO;
        
//        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 110)];
//        imageView.image = [self getGif];
//        _MBPHUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
//        _MBPHUD.bezelView.color = UIColor.whiteColor;
//        _MBPHUD.mode = MBProgressHUDModeIndeterminate;
//        _MBPHUD.customView = imageView;
        _MBPHUD.delegate = [HUDManage shared];
        _MBPHUD.minSize = CGSizeMake(50, 50);
        // 隐藏时候从父控件中移除
        _MBPHUD.removeFromSuperViewOnHide = YES;
        [_MBPHUD hideAnimated:YES afterDelay:1];
    });
}
+ (UIWindow *)topWindow {
    UIWindow *view = nil;
    if (@available(iOS 13.0, *)) {
        view = [UIApplication sharedApplication].windows.lastObject;
    } else {
        view = [UIApplication sharedApplication].delegate.window;
    }
    return view;
}
+ (void)dismiss {
//    UIWindow *view = [self topWindow];
    for (UIWindow *view in [self windows]) {
        [MBProgressHUD hideHUDForView:view animated:NO];
    }
    _MBPHUD = nil;
}
+ (NSArray<UIWindow *>*)windows { // 获取所有window
    NSMutableArray *array = [NSMutableArray array];
    if (@available(iOS 13.0, *)) {
        for (UIWindow *window in [UIApplication sharedApplication].windows) {
            [array addObject: window];
        }
    } else {
        [array addObject:[UIApplication sharedApplication].delegate.window];
    }
    return array;
}
+ (BOOL)isshow {
    return _MBPHUD?YES:NO;
}
+ (UIImage *)getGif {
    NSArray *images = @[[UIImage imageNamed:@"加载动画1"], [UIImage imageNamed:@"加载动画2"], [UIImage imageNamed:@"加载动画3"], [UIImage imageNamed:@"加载动画4"]];
    NSTimeInterval duration = 0.8;
    return [UIImage animatedImageWithImages:images duration:duration];
}
//+ (void)showHUDWithTitle:(NSString *)title {
//    [self showHUDWithTitle:title afterDelay:1];
//}
//+ (void)showHUDWithTitle:(NSString *)title afterDelay:(NSTimeInterval)delay {
//    if (title.length == 0) {
//        return;
//    }
//    [HWProgressHUD showType:(HWProgressHUDTypeText) text:title time:delay];
//}
//+ (void)showLoadingHUD {
//    [self showLoadingHUDWithTitle:@""];
//}
//+ (void)showLoadingHUDWithTitle:(NSString *)title {
//    [HWProgressHUD showType:(HWProgressHUDTypeImages) text:title time:10]; // 设置60秒超时解除 hud
//}
//+ (void)dismiss {
//    [HWProgressHUD dismiss];
//}
//
//+ (BOOL)isshow {
//   return [HWProgressHUD isshow];
//}
//@end

/// 最大宽度
//#define maxwidth ([UIScreen mainScreen].bounds.size.width - 100)
///// 背景颜色
//#define bgColor [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7]
///// 文字大小
//#define label_font [UIFont systemFontOfSize:14]
//#define activityIndicatorViewFrame CGRectMake(0,15,50,50)
//static UIView *currentWindow;
//static NSArray<UIImage *> *_HWProgressHUDImages;
//static HWProgressHUD * HWProgressHUDsingle = nil;
//@interface HWProgressHUD ()
///* 内容label */
//@property (nonatomic, strong) UILabel *textLabel;
///* 菊花 */
//@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;
///* 动画图片 */
//@property (nonatomic, strong) UIImageView *animationImageView;
///* 内容view */
//@property (nonatomic, strong) UIView *contentView;
///* 定时器 */
//@property (nonatomic, strong) NSTimer *timer;
//@end
//
//@implementation HWProgressHUD
//
//+ (void)showType:(HWProgressHUDType)type text:(NSString *)text time:(NSTimeInterval)time {
//    if ([self isshow]) { // 如果显示着 先移除 延迟加载
//        [self dismiss];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [self createHudWithType:type text:text time:time];
//        });
//    } else {
//        [self createHudWithType:type text:text time:time];
//    }
//}
//
//+ (void)createHudWithType:(HWProgressHUDType)type text:(NSString *)text time:(NSTimeInterval)time {
//    UIView *window = [[UIView alloc] init];
//    NSLog(@"%@", [NSThread currentThread]);
//    [[NSOperationQueue mainQueue] addBarrierBlock:^{
//        NSLog(@"%@", [NSThread currentThread]);
//        __weak HWProgressHUD *hud = [self shared];
//        window.backgroundColor = [UIColor clearColor];
//        currentWindow = window;
//        [self reset];
//        
//        UIView *mainView = hud.contentView;
//        
//        hud.textLabel.text = text;
//        [hud.textLabel sizeToFit]; // 文字自适应
//        
//        if (![window.subviews containsObject:mainView]) {
//            [window addSubview:mainView];
//        }
//        
//        CGRect frame = CGRectZero;
//        CGFloat labelHeight = 0;
//        CGFloat labelWidth = 0;
//        if (text.length) {
//            labelHeight = [text boundingRectWithSize:CGSizeMake(maxwidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:hud.textLabel.font, NSFontAttributeName, nil] context:nil].size.height;
//            labelWidth = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, labelHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:hud.textLabel.font, NSFontAttributeName, nil] context:nil].size.width;
//            labelWidth = labelWidth<maxwidth?labelWidth:maxwidth;
//        }
//        [self removeFromSuperview:type];
//        if (type == HWProgressHUDTypeLoading) { // 菊花
//            window.frame = [UIScreen mainScreen].bounds;
//            if (labelHeight) {
//                frame = CGRectMake(0, 0, labelWidth + activityIndicatorViewFrame.size.width, labelHeight + 2*activityIndicatorViewFrame.size.height);
//            } else {
//                CGFloat wh = activityIndicatorViewFrame.size.width+2*activityIndicatorViewFrame.origin.y;
//                frame = CGRectMake(0, 0, wh, wh);
//            }
//            mainView.frame = frame;
//            UIActivityIndicatorView *activityIndicatorView = hud.activityIndicatorView;
//            CGFloat x = (frame.size.width-activityIndicatorViewFrame.size.width)/2;
//            activityIndicatorView.frame = CGRectMake(x, activityIndicatorViewFrame.origin.y, activityIndicatorViewFrame.size.width, activityIndicatorViewFrame.size.height);
//            if (![mainView.subviews containsObject:activityIndicatorView]) {
//                [mainView addSubview:activityIndicatorView];
//            }
//            [activityIndicatorView startAnimating];
//            
//            if (labelHeight) {
//                UILabel *label = hud.textLabel;
//                if (![mainView.subviews containsObject:label]) {
//                    [mainView addSubview:label];
//                }
//                label.text = text;
//                CGFloat y = activityIndicatorViewFrame.size.width+2*activityIndicatorViewFrame.origin.y;
//                label.frame = CGRectMake((frame.size.width-labelWidth)/2, y, labelWidth, labelHeight);
//            }
//            
//            mainView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
//        } else if (type == HWProgressHUDTypeImages) { // 加载动画
//            window.frame = [UIScreen mainScreen].bounds;
//            UIImageView *imageView = hud.animationImageView;
//            mainView.frame = CGRectMake(0, 0, 100, 130);
//            imageView.frame = CGRectMake(10, 10, 80, 110);
//            mainView.backgroundColor = UIColor.whiteColor;
//            mainView.layer.shadowColor = UIColor.blackColor.CGColor;
//            mainView.layer.shadowOffset = CGSizeMake(0,5);
//            mainView.layer.shadowOpacity = 0.1;
//            mainView.layer.shadowRadius = 5;
//            if (![mainView.subviews containsObject:imageView]) {
//                [mainView addSubview:imageView];
//            }
//            mainView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [imageView startAnimating];
//            });
//        } else { // 文字
//            UILabel *label = hud.textLabel;
//            frame = CGRectMake(0, 0, labelWidth + 30, labelHeight + 30);
//            mainView.frame = frame;
//            window.frame = frame;
//            if (labelHeight) {
//                hud.textLabel.frame = CGRectMake((frame.size.width-labelWidth)/2, (frame.size.height-labelHeight)/2, labelWidth, labelHeight);
//                if (![mainView.subviews containsObject:label]) {
//                    [mainView addSubview:label];
//                }
//            }
//            window.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [hud startTimer:time];
//            [self show];
//        });
//    }];
//}
////MARK: 定时器
//- (void)startTimer:(NSTimeInterval)ti  {
//    [self stopTimer];
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:ti target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//}
//
//- (void)stopTimer {
//    if (self.timer) {
//        [self.timer invalidate];
//        self.timer = nil;
//    }
//}
//
//- (void)runTimer {
//    [HWProgressHUD dismiss];
//}
//
////MARK: 重置
//+ (void)reset {
//    HWProgressHUD *hud = [self shared];
//    [hud.contentView removeFromSuperview];
//    [hud.textLabel removeFromSuperview];
//    [hud.animationImageView removeFromSuperview];
//    [hud.activityIndicatorView removeFromSuperview];
////    hud.contentView.backgroundColor = bgColor;
////    hud.contentView.frame = CGRectZero;
////    hud.textLabel.frame = CGRectZero;
////    hud.animationImageView.frame = CGRectZero;
////    hud.activityIndicatorView.frame = CGRectZero;
////    if ([hud.contentView.subviews containsObject:hud.animationImageView] && hud.animationImageView.isAnimating) { // 停止动画
////        [hud.animationImageView stopAnimating];
////    }
////    if ([hud.contentView.subviews containsObject:hud.activityIndicatorView] && hud.activityIndicatorView.isAnimating) { // 停止动画
////        [hud.activityIndicatorView stopAnimating];
////    }
//}
//
////MARK: 对应类型移除控件
//+ (void)removeFromSuperview:(HWProgressHUDType)type {
//    HWProgressHUD *hud = [self shared];
//    switch (type) {
//        case HWProgressHUDTypeLoading: { // 菊花
//            if ([hud.contentView.subviews containsObject:hud.animationImageView]) {
//                [hud.animationImageView removeFromSuperview];
//            }
//        }break;
//        case HWProgressHUDTypeImages: { // 图片动画
//            if ([hud.contentView.subviews containsObject:hud.textLabel]) {
//                [hud.textLabel removeFromSuperview];
//            }
//            if ([hud.contentView.subviews containsObject:hud.activityIndicatorView]) {
//                [hud.activityIndicatorView removeFromSuperview];
//            }
//        }break;
//        default: { // 文字
//            if ([hud.contentView.subviews containsObject:hud.animationImageView]) {
//                [hud.animationImageView removeFromSuperview];
//            }
//            if ([hud.contentView.subviews containsObject:hud.activityIndicatorView]) {
//                [hud.activityIndicatorView removeFromSuperview];
//            }
//        }break;
//    }
//}
//
////+ (NSArray<UIImage *> *)images {
////    if (!_HWProgressHUDImages) {
////        _HWProgressHUDImages = @[[UIImage imageNamed:@"加载动画1"], [UIImage imageNamed:@"加载动画2"], [UIImage imageNamed:@"加载动画3"], [UIImage imageNamed:@"加载动画4"]];
////    }
////    return _HWProgressHUDImages;
////}
//
//+ (void)show {
//    NSLog(@"显示");
//    UIWindow *window = nil;
//    if (@available(iOS 13.0, *)) {
//        window = [UIApplication sharedApplication].windows.firstObject;
//    } else {
//        window = [UIApplication sharedApplication].delegate.window;
//    }
//    if (!currentWindow || [window.subviews containsObject:currentWindow]) {return;}
//    [window addSubview:currentWindow];
//   
//}
//
//+ (void)dismiss {
//    NSLog(@"消失");
//    if (currentWindow) {
//        [[self shared] stopTimer];
//        dispatch_async(dispatch_get_main_queue(), ^{
////            [currentWindow resignKeyWindow];
//            [currentWindow removeFromSuperview];
//            currentWindow = nil;
//        });
//    }
//}
//
//+ (BOOL)isshow {
//    return currentWindow ? YES : NO;
//}
////MARK: - 懒加载
//+ (HWProgressHUD *)shared {
//    static dispatch_once_t once;
//    dispatch_once(&once,^{
//        HWProgressHUDsingle = [[self alloc] init];
//    });
//    return HWProgressHUDsingle;
//}
//- (UIView *)contentView {
//    if (!_contentView) {
//        _contentView = [[UIView alloc] init];
//        _contentView.layer.cornerRadius = 10;
//        _contentView.backgroundColor = bgColor;
//    }
//    return _contentView;
//}
//- (UILabel *)textLabel {
//    if (!_textLabel) {
//        _textLabel = [[UILabel alloc] init];
//        _textLabel.numberOfLines = 0;
//        _textLabel.font = label_font;
//        _textLabel.textAlignment = NSTextAlignmentCenter;
////        _textLabel.translatesAutoresizingMaskIntoConstraints = NO;
//        _textLabel.textColor = [UIColor whiteColor];
//        [_textLabel sizeToFit];
//    }
//    return _textLabel;
//}
//- (UIActivityIndicatorView *)activityIndicatorView {
//    if (!_activityIndicatorView) {
//        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:activityIndicatorViewFrame];
//        [_activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleMedium];
//        [_activityIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleLarge];
//        [_activityIndicatorView setBackgroundColor:[UIColor clearColor]];
//    }
//    return _activityIndicatorView;
//}
//- (UIImageView *)animationImageView {
//    if (!_animationImageView) {
//        _animationImageView = [[UIImageView alloc] init];
//        NSArray *images = @[[UIImage imageNamed:@"加载动画1"], [UIImage imageNamed:@"加载动画2"], [UIImage imageNamed:@"加载动画3"], [UIImage imageNamed:@"加载动画4"]];
//        [_animationImageView setAnimationImages:images];
//        [_animationImageView setAnimationDuration:1]; //设置动画总时间
//        [_animationImageView setAnimationRepeatCount:0]; //设置重复次数,0表示无限
//        _animationImageView.image = images.firstObject;
//    }
//    return _animationImageView;
//}
//
@end


